package com.talking.activities

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.parfoismeng.slidebacklib.registerSlideBack
import com.parfoismeng.slidebacklib.unregisterSlideBack
import com.talking.App
import com.talking.adapter.SearchAdapter
import com.talking.bean.UserBean
import com.talking.databinding.ActivitySearchBinding
import com.talking.util.Network
import com.talking.util.Tools
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class SearchActivity : AppCompatActivity() {
    private lateinit var launcher: ActivityResultLauncher<Intent>
    private var clickPosition: Int=0
    private lateinit var adp: SearchAdapter
    private val data: MutableList<UserBean> =ArrayList()
    private val calls: MutableList<Call> = ArrayList()
    private var nowTab: Int = 0
    private lateinit var binding: ActivitySearchBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.searchEdit.setOnEditorActionListener { _, i, _ ->
            if (i == EditorInfo.IME_ACTION_SEARCH) refresh()
            false
        }
        binding.searchEdit.requestFocus()
        binding.searchTab.addTab(binding.searchTab.newTab().setText("用户"))
        binding.searchTab.addTab(binding.searchTab.newTab().setText("聊天记录"))
        binding.searchTab.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                when(tab.text.toString()){
                    "用户"->nowTab = 0
                    "聊天记录"->nowTab = 1
                }
                refresh()
            }
            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
        adp = SearchAdapter(this,data)
        binding.searchList.adapter=adp
        binding.searchList.onItemClickListener= AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, i: Int, _: Long ->
            clickPosition=i
            if (App.sp.getString("mail","").toString().equals(data[i].mail.toString())){
                launcher.launch(Intent(this@SearchActivity,PersonActivity::class.java).putExtra("mail",data[i].mail.toString()))
            }else{
                val map = HashMap<String, String>()
                map["me_mail"]= App.sp.getString("mail","").toString()
                map["other_mail"]= data[i].mail.toString()
                Network.post(map, "friend/isMyFriend/") { call: Call ->
                    call.enqueue(object : Callback {
                        override fun onFailure(call: Call, e: IOException) { e.printStackTrace() }
                        override fun onResponse(call: Call, response: Response) {
                            runOnUiThread{
                                val str = response.body!!.string()
                                if (JsonParser.parseString(str).asJsonObject.get("msg").asBoolean){
                                    launcher.launch(Intent(this@SearchActivity,PersonActivity::class.java).putExtra("mail",data[i].mail.toString()))
                                }else{
                                    launcher.launch(Intent(this@SearchActivity,ChatActivity::class.java))
                                }
                            }
                        }
                    })
                    calls.add(call)
                }
            }
        }
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult? ->

        }
    }
    private fun refresh(){
        val type:String = if (nowTab==0) "user" else return
        val map = HashMap<String, String>()
        map["type"] = type
        map["kw"] = binding.searchEdit.text.toString()
        data.clear()
        adp.notifyDataSetChanged()
        Network.post(map, "user/search/") { call: Call ->
            call.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }
                override fun onResponse(call: Call, response: Response) {
                    runOnUiThread{
                        val jo = JsonParser.parseString(response.body!!.string()).asJsonObject
                        if (!jo.get("msg").asString.equals("获取成功")){
                            Tools.toast(jo.get("msg").asString)
                        }else{
                            data.addAll(Gson().fromJson<List<UserBean>>(jo.get("data").asJsonArray, object : TypeToken<List<UserBean?>?>() {}.type))
                            adp.notifyDataSetChanged()
                        }
                    }
                }
            })
            calls.add(call)
        }
        registerSlideBack { finish() }
    }
    override fun onDestroy() {
        super.onDestroy()
        unregisterSlideBack()
        for (c in calls)c.cancel()
    }
}